package com.ruoyi.car.websocket;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.car.domain.OrderInfo;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;


/**
 * @author : Li
 * @date : 2024-08-21 11:00
 * @description :
 **/
@ServerEndpoint("/websocket")
@Component
public class WebSocket {

    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    private Session session;


    @OnOpen
    public void opOpen(Session session){
        this.session = session;
        webSockets.add(this);

        System.out.println("【websocket】有新的连接 总数：{}"+webSockets.size());
    }

    @OnClose
    public void onClose(){
        //关闭的话移除
        webSockets.remove(this);
        System.out.println("【websocket】连接断开 总数：{}"+webSockets.size());
    }

    @OnMessage
    public void onMessage(String message){
        //收到消息
        System.out.println("【websocket】收到客户端发来的消息：{}"+message);
    }



    public void sendMessage(String message) {

            for (WebSocket webSocket : webSockets) {
                System.out.println("【websocket】广播消息 message={}" + message);
                JSON.parseObject(message, OrderInfo.class);
                try {
                    webSocket.session.getBasicRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    }


    @OnError
    public void onError(Session session,Throwable throwable){
        //异常
        System.out.println("onError");
    }

}
